(function () {
  'use strict';

  angular
    .module('client')
    .run(runBlock);

  runBlock.$inject = ['$rootScope', '$state', '$location', '$cookies', 'AUTH_EVENTS', 'TEST_PLUS_AUTH', 'AuthService'];
  function runBlock($rootScope, $state, $location, $cookies, AUTH_EVENTS, TEST_PLUS_AUTH, AuthService) {

    $rootScope.$on('$stateChangeStart', function (event, next) {
      if (!next.data) {
        return;
      }

      var isTestPlusAuth = ((-1 !== document.referrer.indexOf(TEST_PLUS_AUTH.CN) ||
      -1 !== document.referrer.indexOf(TEST_PLUS_AUTH.EN)) && $cookies.getObject('testplus_auth'));
      if (isTestPlusAuth) {
        AuthService.saveToken($cookies.getObject('testplus_auth').token);
        return;
      }

      var needAuthenticated = next.data.needAuthenticated;
      var isAuthenticated = AuthService.isAuthenticated();
      if (needAuthenticated && !isAuthenticated) {
        event.preventDefault();
        $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
      } else if (isAuthenticated && next.data.goDash) {
        event.preventDefault();
        $state.go('device');
      }
    });

    $rootScope.$on(AUTH_EVENTS.notAuthenticated, function (event) {
      var host = $location.host();
      if (-1 !== host.indexOf(TEST_PLUS_AUTH.remoteCN)) {
        window.top.location = TEST_PLUS_AUTH.CN;
      } else if (-1 !== host.indexOf(TEST_PLUS_AUTH.remoteEN)) {
        window.top.location = TEST_PLUS_AUTH.EN;
      } else {
        $state.go('auth.login');
      }
    });
  }

}());
